/**
 * Created by callmesoul on 2017/4/10.
 */
// var jwt = require('jsonwebtoken');
var WechatApi = require('co-wechat-api');
module.exports = (options,app) => {
    return async function(ctx,next) {
        var host=ctx.request.host.split(':');
		console.log("host",host);
		console.log("ctx.request.url",ctx.request.url);
        host=host[0];
        var url='http://'+host+ctx.request.url;
		console.log(".url",url);
        var api=new WechatApi(ctx.session.wechat.appId,ctx.session.wechat.appSecret,async function () {
            var wechat =await ctx.model.Wechat.findOne({where:{id:ctx.session.wechat.id}});
			console.log("cwechat&&wechat.accessToken",wechat&&wechat.accessToken);
            if(wechat&&wechat.accessToken){
                return JSON.parse(wechat.accessToken);
            }else {
                return false;
            }
        },async function (token) {
			console.log("token",token);
            await ctx.model.Wechat.update({accessToken:JSON.stringify(token)},{where:{id:ctx.session.wechat.id}});
        });
        var parms={
            debug:true,
            jsApiList:['onMenuShareAppMessage','onMenuShareTimeline','chooseWXPay','chooseImage','uploadImage','getLocation'],
            url:url
        };
        var resule = await api.getJsConfig(parms);
        ctx.session.jssdk=resule;
        await next();
    };
};
